<?php

namespace app\service;

use app\model\AdminModel;
use app\exception\BusinessException;
use Tinywan\Jwt\JwtToken;

class AuthService
{
    /**
     * 验证管理员用户名密码
     * @param string $username
     * @param string $password
     * @return array|null
     * @throws BusinessException
     */
    public static function verify(string $username, string $password)
    {
        $admin = AdminModel::where('username', $username)->first();
        if (!$admin) {
            return null;
        }

        // 验证密码
        if (!password_verify($password, $admin->password)) {
            return null;
        }

        // 检查状态
        if ($admin->status != 1) {
            throw new BusinessException('账号已被禁用');
        }

        return [
            'id' => $admin->id,
            'username' => $admin->username,
            'email' => $admin->email,
            'status' => $admin->status,
            'created_at' => $admin->created_at,
            'updated_at' => $admin->updated_at
        ];
    }

    /**
     * 获取当前登录用户
     * @return array
     * @throws BusinessException
     */
    public static function user()
    {
        $payload = JwtToken::getCurrentId();
        if (!isset($payload['admin_id'])) {
            throw new BusinessException('未登录或登录已过期');
        }

        $admin = AdminModel::find($payload['admin_id']);
        if (!$admin) {
            throw new BusinessException('用户不存在');
        }

        return [
            'id' => $admin->id,
            'username' => $admin->username,
            'email' => $admin->email,
            'status' => $admin->status,
            'created_at' => $admin->created_at,
            'updated_at' => $admin->updated_at
        ];
    }
}